import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const userId = parseInt(id)

    if (isNaN(userId)) {
      return NextResponse.json({
        success: false,
        message: '无效的用户ID'
      }, { status: 400 })
    }

    // 并行执行所有查询以提高性能
    const [user, recentHealthLogs, healthStats] = await Promise.all([
      // 1. 查询用户基本信息（不包含关联数据）
      prisma.smoke_user.findFirst({
        where: {
          id: userId,
          delete_time: 0
        },
        select: {
          id: true,
          mobile: true,
          cc: true,
          name: true,
          avatar: true,
          gender: true,
          age: true,
          birthday: true,
          height: true,
          weight: true,
          city: true,
          create_time: true,
          last_active_time: true
        }
      }),
      
      // 2. 单独查询最近的健康记录
      prisma.yh_logs.findMany({
        where: {
          user_id: userId,
          deleted_at: 0
        },
        select: {
          id: true,
          type: true,
          device_id: true,
          data: true,
          timestamp: true,
          created_at: true
        },
        orderBy: {
          created_at: 'desc'
        },
        take: 10
      }),
      
      // 3. 统计各类型健康数据
      prisma.yh_logs.groupBy({
        by: ['type'],
        where: {
          user_id: userId,
          deleted_at: 0
        },
        _count: {
          type: true
        }
      })
    ])

    if (!user) {
      return NextResponse.json({
        success: false,
        message: '用户不存在'
      }, { status: 404 })
    }

    // 计算总的健康记录数量
    const totalHealthLogs = healthStats.reduce((sum, stat) => sum + stat._count.type, 0)

    // 计算实际年龄
    let calculatedAge = user.age || 0
    if (user.birthday) {
      try {
        const birthDate = new Date(user.birthday)
        const today = new Date()
        let age = today.getFullYear() - birthDate.getFullYear()
        const monthDiff = today.getMonth() - birthDate.getMonth()
        
        // 如果还没到生日，年龄减1
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
          age--
        }
        
        if (age > 0 && age < 120) {
          calculatedAge = age
        }
      } catch (error) {
        console.error('计算年龄失败:', error)
      }
    }

    // 格式化用户数据
    const formattedUser = {
      id: Number(user.id),
      mobile: user.mobile,
      cc: user.cc,
      name: user.name,
      avatar: user.avatar,
      gender: user.gender,
      age: calculatedAge,
      birthday: user.birthday,
      height: user.height,
      weight: user.weight,
      city: user.city,
      createTime: user.create_time ? new Date(user.create_time * 1000).toISOString() : null,
      lastActiveTime: user.last_active_time ? new Date(user.last_active_time * 1000).toISOString() : null,
      totalHealthLogs,
      recentHealthLogs: recentHealthLogs.map(log => ({
        id: Number(log.id),
        type: log.type,
        device_id: log.device_id,
        data: log.data,
        timestamp: log.timestamp.toString(),
        created_at: log.created_at.toString()
      })),
      healthStats: healthStats.map(stat => ({
        type: stat.type,
        count: stat._count.type
      }))
    }

    return NextResponse.json({
      success: true,
      data: formattedUser,
      message: '用户详情获取成功'
    })
  } catch (error) {
    console.error('User detail query error:', error)
    return NextResponse.json({
      success: false,
      error: 'Database query failed',
      message: '用户详情查询失败'
    }, { status: 500 })
  }
}